<template>
  <div id="world-map-area">
    <div id="world-map-content"></div>
  </div>
</template>

<script>
import echartMixins from '@/utils/resizeMixins'
import { createNamespacedHelpers } from 'vuex'
import { countries as COUNTRIES } from '@/config/countries'
const { mapState } = createNamespacedHelpers('screen')
import WorldMapJSON from 'echarts/map/json/world.json' 
// import GeoCoordMap from '../worldGeoMap'

export default {
  mixins: [echartMixins],
  data () {
    return {
      nameMap: []
    }
  },
  computed: {
    ...mapState(['adminScreenData'])
  },
  watch: {
    'adminScreenData.countrydata': {
      deep: true,
      handler () {
        this.draw()
      }
    }
  },
  created () {
    this.$echarts.registerMap('world', WorldMapJSON)
  },
  mounted () {
    this.draw()
  },
  methods: {
    makeNameMap () {
      const nameMap = {}
      COUNTRIES.forEach(c => {
        nameMap[c.ENLabel] = this.$store.state.locale === 'en-US' ? c.ENLabel : c.label
      })
      this.nameMap = Object.freeze(nameMap)
    },
    makeData () {
      const data = []
      _.forEach(this.adminScreenData.countrydata, (v, k) => {
        const item = {}
        item.name = this.getCountryByLang(v.country)
        item.value = v.totalelectric
        item.totalelectric = v.totalelectric
        item.todayelectric = v.todayelectric
        item.co2 = v.co2
        data.push(item)
      })
      return data
    },
    draw () {
      this.makeNameMap()
      // 基于准备好的dom，初始化echarts实例
      if (!this._chart) {
        this._chart = this.$echarts.init(document.getElementById('world-map-content'))
      } 
      if (!_.isNil(this.timer)) {
        clearInterval(this.timer)
        this.timer = null
      }
      const data = this.makeData()
      const valuesArray = data.map(s => s.value)
      const min = _.min(valuesArray)
      const max = _.max(valuesArray)
      const KeyMaps = {
        totalelectric: this.$t('jhOHkzJphJwwP6j_SH81R'),
        todayelectric: this.$t('B7hgWZ-ZSurAsJJvV9AIe'),
        co2: this.$t('Ox6sE2vYcyDNl_W2AP8Gq'),
      }
      //  ----------------------------------------------------------------
      const option = {
        tooltip: {
          trigger: 'item',
          padding: [10,20],
          color: '#fff',
          backgroundColor: "rgba(26,57,97,0.8)",
          borderColor: '#aee9fb',
          borderWidth: 1,
          borderRadius: 6,
          textStyle: {
            align: 'left',
            lineHeight: 20
          },
          formatter: function (params) {
            // console.log(arguments)
            if (params.data) {
              return '<strong style="color:rgb(208,177,12);">' + params.name + '</strong><br/>' + 
                KeyMaps.totalelectric + ' : ' +  params.data.totalelectric + ' kWh<br/>' + 
                KeyMaps.todayelectric + ' : ' +  params.data.todayelectric + ' kWh<br/>' + 
                KeyMaps.co2 + ' : ' +  params.data.co2 + ' kg'
            }
            return ''
          }
        },
        geo: {
          name: this.$t('uB7JO-nVYWp5k2_H0ViiE'),
          map: 'world',
          zlevel: 1,
          roam: false,
          nameMap: this.nameMap,
          zoom: 1,
          aspectScale: 1.1, // 长宽比
          itemStyle: {
            borderColor: '#2ab8ff',
            borderWidth: 0.5,
            areaColor: '#12235c',
            shadowColor: '#182f68',
            shadowOffsetX: 2,
            shadowOffsetY: 2
          },
          emphasis: {
            itemStyle: {
              areaColor: 'rgb(0,140,93)',
              borderWidth: 0
            },
            label: {
              color: '#fff'
            }
          }
        },
        series: [{
          name: this.$t('uB7JO-nVYWp5k2_H0ViiE'),
          type: 'map',
          map: 'world',
          geoIndex: 0,
          data,
          zoom:0.8
        }]
      }
      this._chart.setOption(option)
      this.interval(data)
      this.bindEvent(data)
    },

    interval (data) {
      let index = -1;
      const myChart = this._chart
      this.timer = setInterval(function () {
          // 隐藏提示框
          myChart.dispatchAction({
              type: 'hideTip',
              seriesIndex: 0,
              dataIndex: index
          });
          // 显示提示框
          myChart.dispatchAction({
              type: 'showTip',
              seriesIndex: 0,
              dataIndex: index + 1
          });
          // 取消高亮指定的数据图形
          myChart.dispatchAction({
              type: 'downplay',
              seriesIndex: 0,
              dataIndex: index
          });
          // 高亮指定的数据图形
          myChart.dispatchAction({
              type: 'highlight',
              seriesIndex: 0,
              dataIndex: index + 1
          });
          index++;
          if (index >= data.length) {
              index = -1;
          }
      }, 2000);
    },

    bindEvent (data) {
      const myChart = this._chart
      myChart.off('mousemove')
      myChart.on('mousemove', e => {
        // 鼠标移入静止播放
        clearInterval(this.timer);
        this.timer = null
        // 取消高亮
        myChart.dispatchAction({
            type: 'downplay',
            seriesIndex: 0
        });
        // 高亮当前
        myChart.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: e.dataIndex
        });
        // 显示当前浮层
        myChart.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: e.dataIndex
        });
      }); 
      myChart.off('mouseout')
      myChart.on('mouseout', e => {
        clearInterval(this.timer);
        this.timer = null
        // 鼠标移出后先把上次的高亮取消
        myChart.dispatchAction({
            type: 'downplay',
            seriesIndex: 0,
            dataIndex: e.dataIndex
        }); 
        // 再次播放
        this.interval(data)
      })
    }
  },
  beforeDestroy () {
    !_.isNil(this.timer) && clearInterval(this.timer)
  }
}
</script>

<style lang="stylus" scoped>
#world-map-area
  width calc(100% - 20px)
  height calc(100% - 40px)
  position relative
  left 10px
  top 40px
#world-map-content
  width 100%
  height 100%
</style>
